package www.lagou.dao;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import www.lagou.utils.DateUtils;
import www.lagou.utils.DruidUtils;

import java.sql.Connection;
import java.sql.SQLException;

public class AccountDao {

    public void  transfer(){
        QueryRunner qr=new QueryRunner();

        Connection connection= DruidUtils.getConnection();

        try {
            connection.setAutoCommit(false);

            String sql="select balance from account where card=?";
            Double balance = (Double)qr.query(connection, sql, new ScalarHandler<>(), "1122334455");
            if(balance<5000){
                System.out.println("账户余额不足无法转账");
                return;
            }

            String sql2="update account set balance=balance - ? where card=?";
            qr.update(connection,sql2,5000,"1122334455");

            String sql3="update account set balance=balance + ? where card=?";
            qr.update(connection,sql3,5000,"55443332211");

            String sql4="insert into transaction values(?,?,?,?,?)";
            Object[] param={null,"1122334455","转出",5000, DateUtils.getDateFormart()};
            qr.update(connection,sql4,param);

            String sql5="insert into transaction values(?,?,?,?,?)";
            Object[] param2={null,"55443332211","转入",5000, DateUtils.getDateFormart()};
            qr.update(connection,sql5,param2);

            connection.commit();
            System.out.println("转账成功");
        } catch (SQLException e) {
            try {
                connection.rollback();
                System.out.println("转账失败");
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        } finally {
        }
    }
}
